
#import <Security/Security.h>
#import <CoreFoundation/CoreFoundation.h>

#import "GesturePasswordController.h"
#import "StartPageController.h"
#import "QRTabbarController.h"
#import "RequestNetWork.h"
#import "Base64.h"
#import "PromptInfoView.h"


#import "KeychainItemWrapper/KeychainItemWrapper.h"

@interface GesturePasswordController ()
{
    int count;
     NSUserDefaults * userInfo;
    
}

@property (nonatomic,strong) GesturePasswordView * gesturePasswordView;

@end

@implementation GesturePasswordController {
    NSString * previousString;
    NSString * password;
}

@synthesize gesturePasswordView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        userInfo = [NSUserDefaults standardUserDefaults];
        count = 5;
       

    }
    return self;
}

-(void)setComein:(NSString *)comein
{
    _comein = comein;
    if ([comein isEqualToString:@"reset"]) {
        [self clear];
        [self reset];
    }
    else if([comein isEqualToString:@"after"])
    {
         [userInfo setValue:@"2" forKey:@"guestureCount"];//解决手势黑屏问题
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    previousString = [NSString string];
    password = [userInfo objectForKey:GUESTUREKEY];
    if ([password isEqualToString:@""] || password == nil) {
        
        [self reset];
    }
    else {
        [self verify];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 验证手势密码
- (void)verify{
    gesturePasswordView = [[GesturePasswordView alloc]initWithFrame:[UIScreen mainScreen].bounds];
//    gesturePasswordView.hiddenOrNot = _comein;
    [gesturePasswordView.tentacleView setRerificationDelegate:self];
    [gesturePasswordView.tentacleView setStyle:1];
    [gesturePasswordView setGesturePasswordDelegate:self];
    gesturePasswordView.hiddenOrNot = YES;
    [self.view addSubview:gesturePasswordView];
}

#pragma mark - 重置手势密码
- (void)reset{
    gesturePasswordView = [[GesturePasswordView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [gesturePasswordView.tentacleView setResetDelegate:self];
    [gesturePasswordView.tentacleView setStyle:2];
    gesturePasswordView.hiddenOrNot = NO;
    [gesturePasswordView setGesturePasswordDelegate:self];
    [self.view addSubview:gesturePasswordView];
}

#pragma mark - 判断是否已存在手势密码
- (BOOL)exist{
    password = [userInfo objectForKey:GUESTUREKEY];
    if ([password isEqualToString:@""] || password == nil)return NO;
    return YES;
}

#pragma mark - 清空记录
- (void)clear{
    [userInfo setValue:@"" forKey:GUESTUREKEY];
}

#pragma mark - 改变手势密码
- (void)change{
    
}

#pragma mark - 忘记手势密码
- (void)forget{
    if ([_comein isEqualToString:@"first"]) {
        self.GoStartPage(@"yes");
    }
    else if ([_comein isEqualToString:@"after"])
    {
        self.GoStartPage(@"after");
    }
    else
    {
        if ([_comein isEqualToString:@"reset"]) {
            if (_fixGuesture) {
                self.fixGuesture(@"no");
            }
            
        }
//        self.fixGuesture(@"no");
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    [userInfo setObject:nil forKey:@"login"];
    [userInfo setObject:@"0" forKey:@"gesture"];
    [self clear];
}

- (BOOL)verification:(NSString *)result{
    if ([result isEqualToString:password]) {
        [gesturePasswordView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
        [gesturePasswordView.state setText:NSLocalizedString(@"inputGuestureSuccess", nil)];
        
        if ([_comein isEqualToString:@"after"]) {
            [userInfo setValue:@"1" forKey:@"guestureCount"];
            QRTabbarController * rqtbc = [[QRTabbarController alloc]init];
            [self.navigationController pushViewController:rqtbc animated:YES];
        }
        if ([_comein isEqualToString:@"reset"]) {
            [self.view removeFromSuperview];
    
        }
        if ([_comein isEqualToString:@"first"]) {
            QRTabbarController * rqtbc = [[QRTabbarController alloc]init];
            [self.navigationController pushViewController:rqtbc animated:YES];
            [userInfo setValue:@"1" forKey:@"guestureCount"];
        }
        return YES;
    }
    count --;
    if (count == 0) {
        [userInfo setObject:nil forKey:@"login"];
        [userInfo setObject:@"0" forKey:@"gesture"];
        [self clear];
        NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
        [postDict setValue:@"logout" forKey:@"startUp"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"startUp" object:postDict];
    }
    [gesturePasswordView.state setTextColor:[UIColor redColor]];
    NSString * locaStringOne = NSLocalizedString(@"guestureError", nil);
    NSString * locaStringTwo = NSLocalizedString(@"guestureChange", nil);
     [gesturePasswordView.state setText:[NSString stringWithFormat:@"%@%d%@",locaStringOne,count,locaStringTwo]];
    return NO;
}

- (BOOL)resetPassword:(NSString *)result{
    if ([previousString isEqualToString:@""]) {
        previousString=result;
        [gesturePasswordView.tentacleView enterArgin];
        [gesturePasswordView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
        [gesturePasswordView.state setText:NSLocalizedString(@"inputGuesture", nil)];
        return YES;
    }
    else {
        if ([result isEqualToString:previousString]) {
            [userInfo setValue:result forKey:GUESTUREKEY];
             NSString *encrypotoResult=[NSString stringWithFormat:@"%@",[result base64EncodedString]];
            RequestNetWork * rnw = [[RequestNetWork alloc]init];
            NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
            [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
            [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
            [postDict setValue:encrypotoResult forKey:@"gesture"];
            __weak GesturePasswordController * weakSelf = self;
            [rnw initWithPath:POST(MODIYFGESTURE) params:postDict block:^(id downLoadData, id error) {
                if ([downLoadData objectForKey:@"data"]) {
                    [weakSelf keepData];
                }
                else
                {
                        [PromptInfoView showMessage:NSLocalizedString(@"setGuesturefail", nil)];
                        if (_fixGuesture) {
                            _fixGuesture(@"no");
                        [weakSelf back];
                    }
                    
                }
            }
           ];
            return YES;
        }
        else{
            previousString =@"";
            [gesturePasswordView.state setTextColor:[UIColor redColor]];
            [gesturePasswordView.state setText:NSLocalizedString(@"inputAgain", nil)];
            return NO;
        }
    }
}

-(void)keepData
{
    [gesturePasswordView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
    [gesturePasswordView.state setText:NSLocalizedString(@"saveGuesture", nil)];
    [userInfo setValue:@"1" forKey:@"gesture"];
    [userInfo setValue:@"1" forKey:@"guestureCount"];
    [userInfo synchronize];
    if (_fixGuesture) {
        _fixGuesture(@"yes");
    }
    [self back];
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
